package com.ruoyi.recruit.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.recruit.constant.RecruitConstants;
import com.ruoyi.recruit.domain.RecruitContent;
import com.ruoyi.recruit.domain.RecruitUserWritten;
import com.ruoyi.recruit.mapper.RecruitContentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.recruit.mapper.RecruitUserMapper;
import com.ruoyi.recruit.domain.RecruitUser;
import com.ruoyi.recruit.service.IRecruitUserService;
import com.ruoyi.common.core.text.Convert;

/**
 * 应聘人员信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2022-05-05
 */
@Service
public class RecruitUserServiceImpl extends ServiceImpl<RecruitUserMapper, RecruitUser> implements IRecruitUserService
{
    @Autowired
    private RecruitContentMapper recruitContentMapper;

    @Autowired
    private RecruitUserMapper recruitUserMapper;

    /**
     * 查询应聘人员信息
     * 
     * @param userId 应聘人员信息主键
     * @return 应聘人员信息
     */
    @Override
    public RecruitUser selectRecruitUserByUserId(Long userId)
    {
        return baseMapper.selectRecruitUserByUserId(userId);
    }

    /**
     * 查询应聘人员信息列表
     * 
     * @param recruitUser 应聘人员信息
     * @return 应聘人员信息
     */
    @Override
    public List<RecruitUser> selectRecruitUserList(RecruitUser recruitUser)
    {
        List<RecruitUser> userList = baseMapper.selectRecruitUserList(recruitUser);
        for(RecruitUser user : userList){
            String finishTime = user.getFinishTime();
            String birthdayTime = user.getBirthday();
            SimpleDateFormat sdf1 = new SimpleDateFormat ("EEE MMM dd HH:mm:ss Z yyyy", Locale.UK);
            try {
                Date finish = sdf1.parse(finishTime);
                finishTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, finish);
            } catch (ParseException e) {
            }
            try {
                Date birthday = sdf1.parse(birthdayTime);
                birthdayTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, birthday);
            } catch (ParseException e) {
            }
            user.setFinishTime(finishTime);
            user.setBirthday(birthdayTime);
        }
        return userList;
    }

    /**
     * 新增应聘人员信息
     * 
     * @param recruitUser 应聘人员信息
     * @return 结果
     */
    @Override
    public int insertRecruitUser(RecruitUser recruitUser)
    {
        recruitUser.setCreateTime(DateUtils.getNowDate());
        return baseMapper.insert(recruitUser);
    }

    /**
     * 修改应聘人员信息
     * 
     * @param recruitUser 应聘人员信息
     * @return 结果
     */
    @Override
    public int updateRecruitUser(RecruitUser recruitUser)
    {
        recruitUser.setUpdateTime(DateUtils.getNowDate());
        return baseMapper.updateById(recruitUser);
    }

    /**
     * 批量删除应聘人员信息
     * 
     * @param userIds 需要删除的应聘人员信息主键
     * @return 结果
     */
    @Override
    public int deleteRecruitUserByUserIds(String userIds)
    {
        return baseMapper.deleteBatchIds(Arrays.asList(Convert.toLongArray(userIds)));
    }

    /**
     * 删除应聘人员信息信息
     * 
     * @param userId 应聘人员信息主键
     * @return 结果
     */
    @Override
    public int deleteRecruitUserByUserId(Long userId)
    {
        return baseMapper.deleteById(userId);
    }

    /**
     * 校验身份证号是否唯一
     *
     * @param recruitUser 身份证号
     * @return 结果
     */
    @Override
    public String checkIdCardUnique(RecruitUser recruitUser){
        Long userId = StringUtils.isNull(recruitUser.getUserId()) ? -1L : recruitUser.getUserId();
        RecruitUser info = baseMapper.selectOne(new LambdaQueryWrapper<RecruitUser>()
                .eq(RecruitUser::getIdCard, recruitUser.getIdCard())
                .eq(RecruitUser::getRecruitId, recruitUser.getRecruitId()).last("limit 1"));
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue())
        {
            return RecruitConstants.RECRUIT_USER_NOT_UNIQUE;
        }
        return RecruitConstants.RECRUIT_USER_UNIQUE;
    }

    /**
     * 根据身份证号查询报名人员
     *
     * @param idCard 身份证号
     * @return 结果
     */
    @Override
    public RecruitUser checkRecruitUser(String idCard, Long contentId){
        RecruitUser info = baseMapper.selectOne(new LambdaQueryWrapper<RecruitUser>()
                .eq(RecruitUser::getIdCard, idCard)
                .eq(RecruitUser::getContentId, contentId).last("limit 1"));
        return info;
    }

    /**
     * 导入应聘人员信息
     *
     * @param userList 应聘人员信息
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<RecruitUser> userList, Long recruitId, boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(userList) || userList.size() == 0)
        {
            throw new ServiceException("导入应聘人员信息数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (RecruitUser user : userList)
        {
            int row = 1;
            try
            {
                user.setRecruitId(recruitId);
                // 获取招聘计划
                RecruitContent recruitContent = recruitContentMapper.selectOne(new LambdaQueryWrapper<RecruitContent>()
                        .eq(RecruitContent::getPostCode, user.getPostCode())
                        .eq(RecruitContent::getPostName, user.getPostName())
                        .eq(RecruitContent::getRecruitId, recruitId).last("limit 1"));
                if(StringUtils.isNull(recruitContent)){
                    failureNum++;
                    failureMsg.append("<br/>" + successNum + "、第：" + row + " 行招聘计划不存在");
                    continue;
                }
                user.setContentId(recruitContent.getContentId());
                // 获取应聘人员信息
                RecruitUser info = recruitUserMapper.selectOne(new LambdaQueryWrapper<RecruitUser>()
                        .eq(RecruitUser::getIdCard, user.getIdCard())
                        .eq(RecruitUser::getRecruitId, recruitId).last("limit 1"));
                if(StringUtils.isNull(info)){
                    user.setCreateBy(operName);
                    this.insertRecruitUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、第" + row + " 行应聘人员信息导入成功");
                }else if(isUpdateSupport){
                    user.setUserId(info.getUserId());
                    user.setUpdateBy(operName);
                    this.updateRecruitUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、第" + row + " 行应聘人员信息更新成功");
                }else{
                    failureNum++;
                    failureMsg.append("<br/>" + successNum + "、第：" + row + " 行应聘人员信息已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、第" + row + " 行应聘人员信息导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
            row++;
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
